/**
 * Copyright (C) 2011 Taobao Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.taobao.jaket.impl;

import java.lang.reflect.Type;
import java.util.Map;

import com.taobao.jaket.Builder;
import com.taobao.jaket.JaketContext;
import com.taobao.jaket.adapter.CustomTypeAdapter;
import com.taobao.jaket.adapter.CustomTypeAdapters;
import com.taobao.jaket.adapter.DefaultTypeAdapters;
import com.taobao.jaket.adapter.TypeAdapter;

/**
 * Represent the context for {@link Builder}
 * <p>
 * {@link JaketContext} maintains all type adapters in {@link Builder} when
 * building {@link TypeDefinition}s
 * </p>
 * 
 * @author Xueqiang Mi
 */
public class DefaultJaketContext implements JaketContext {

    private static final Map<Type, CustomTypeAdapter> customTypeAdapters = CustomTypeAdapters.getAdapters();

    private static final Map<Type, TypeAdapter> defaultTypeAdapters = DefaultTypeAdapters.getAdapters();

    /**
     * register a custom type adapter to builder
     * 
     * @param type
     * @param typeAdapter
     */
    public void registerTypeAdapter(Type type, CustomTypeAdapter typeAdapter) {
        if (!customTypeAdapters.containsKey(type)) {
            throw new IllegalStateException("duplicated type adapter");
        }
        customTypeAdapters.put(type, typeAdapter);
    }

    public TypeAdapter getTypeAdapter(Type type) {
        for (CustomTypeAdapter typeAdapter : customTypeAdapters.values()) {
            if (typeAdapter.accept(type)) {
                return typeAdapter;
            }
        }
        if (defaultTypeAdapters.containsKey(type)) {
            return defaultTypeAdapters.get(type);
        }
        return null;
    }
}
